package com.caikun.shopping_car_serve.service.impl;

import com.caikun.model.common.Result;
import com.caikun.model.entity.ServiceEntity;
import com.caikun.model.entity.ShoppingCar;
import com.caikun.model.vo.ShoppingCarRecord;
import com.caikun.model.vo.ShoppingCarVO;
import com.caikun.shopping_car_serve.mapper.ShoppingCarMapper;
import com.caikun.shopping_car_serve.service.ShoppingCarService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 购物车表(ShoppingCar)表服务实现类
 *
 * @author makejava
 * @since 2025-07-18 09:23:29
 */
@Slf4j
@Service("shoppingCarService")
public class ShoppingCarServiceImpl implements ShoppingCarService {
    @Autowired
    private ShoppingCarMapper ShoppingCarMapper;

    @Override
    public void addToShoppingCar(Integer userId, Integer serviceType, Integer packageId, Double price) {
        // 查询有无存在的userId-packageId/serviceId
        ShoppingCar shoppingCar = ShoppingCarMapper.queryByUserIdAndServiceTypeAndpackageId(userId, serviceType, packageId);
        if(shoppingCar == null) {
            // 不存在，直接插入
            shoppingCar = new ShoppingCar();
            shoppingCar.setUserId(userId);
            shoppingCar.setServiceType(serviceType);
            shoppingCar.setServiceId(serviceType == 0 ? packageId : 6379);
            shoppingCar.setPackageId(serviceType == 1 ? packageId : 6379);
            shoppingCar.setPrice(price);
            shoppingCar.setCount(1);
            ShoppingCarMapper.insert(shoppingCar);
        } else {
//             存在，更新数量
            ShoppingCarMapper.updateAdd(userId, serviceType, packageId);
        }
    }

    @Override
    public void removeFromShoppingCar(Integer userId, Integer serviceType, Integer packageId) {
        log.info("删除商品id -- {}", packageId);
        // 实现从购物车删除的逻辑
        ShoppingCar shoppingCar = ShoppingCarMapper.queryByUserIdAndServiceTypeAndpackageId(userId, serviceType, packageId);
        if(shoppingCar != null) {
            if(shoppingCar.getCount() > 1){
                ShoppingCarMapper.updateDelete(userId, serviceType, packageId);
           }
            else {
                log.info("删除商品 -- {}", shoppingCar);
                ShoppingCarMapper.delete(shoppingCar);
            }
        } else {
            throw new IllegalArgumentException("商品不存在于购物车");
        }
    }

    public ShoppingCarVO getshoppingCar(Integer userId) {
        List<ShoppingCarRecord> shoppingCarRecords = ShoppingCarMapper.getshoppingCar(userId);
        Double totalPrice = 0.0;
        for (ShoppingCarRecord shoppingCarRecord : shoppingCarRecords) {
            totalPrice += shoppingCarRecord.getShopPrice() * shoppingCarRecord.getShopcount();
        }
        return new ShoppingCarVO(shoppingCarRecords, totalPrice);
    }

    @Override
    public int deleteByuserId(Integer userId) {
        return ShoppingCarMapper.deleteByuserId(userId);
    }

}
